package com.adu.springbootdemo.service;

import cn.hutool.core.util.ZipUtil;
import com.adu.springbootdemo.domain.*;
import com.adu.springbootdemo.service.impl.IUserService;
import com.adu.springbootdemo.util.DbUtil;
import com.adu.springbootdemo.util.VelocityUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.adu.springbootdemo.mapper.UserMapper;
import cn.hutool.core.io.FileUtil;
import org.springframework.util.FileCopyUtils;

@Service
public class UserService implements IUserService{
    @Autowired
    private UserMapper userMapper;
//
//    @Override
//    @Excel
    public List<User> findAll(){
         return userMapper.findAll();
//        return query();
    }
//
//    @Override
//    public void Insert(User user){
//        userMapper.Insert(user);
//    }
//
//    @Override
//    public void Update(User user){
//        userMapper.Update(user);
//    }
//
//    @Override
//    public void Delete(int id){
//        userMapper.Delete(id);
//    }
    public List<User> query()  {
        List<User> gs = new ArrayList<>();
        // try{
        //     Connection conn = DbUtil.getConnection();
        //     Statement stmt = conn.createStatement();
        //     ResultSet rs = stmt.executeQuery("SELECT * FROM user");            
        //     User user = null;
        //     while(rs.next()){
        //         user = new User();
        //         user.setId(rs.getInt("id"));
        //         user.setName(rs.getString("name"));
        //         gs.add(user);
        //     }
        // }catch(Exception e){
          
        // }
        return gs;
    }
    @Override
    public void coding(GeneratePara generatePara) {
        
        // DbConnectInfo dbConnectInfo=new DbConnectInfo();
        // generatePara.dbInfo.forEach((item)->{
        //     dbConnectInfo.TableName=item.TABLE_NAME;
        //     List<DbInfo> info=Generate(dbConnectInfo);
        // });
//        VelocityUtil.Generate(generatePara);
        
    }
    // 清洗数据
    public List<Db> wash(List<DbInfo> data){
        Info info =new Info();
        List<Db> tables=new ArrayList<>();
        Map<String,List<DbInfo>> group=data.stream().collect(Collectors.groupingBy(DbInfo::getTABLE_NAME));
        for(Map.Entry<String,List<DbInfo>> entry:group.entrySet()){
            Db db =new Db();
            db.setTableName(entry.getKey());
            db.setTableComment(entry.getValue().get(0).TABLE_COMMENT);
            db.setDbinfo(entry.getValue());
            db.setShow(0);
            tables.add(db);
        }
        info.setDb(tables);
        return tables;

    }

    public void moveFile(String path,String groupPath) throws IOException {
        System.out.print("path: "+path);
        System.out.print("GroupPath: "+groupPath);
        String projectName=groupPath.split("\\\\")[2];
        org.aspectj.util.FileUtil.copyDir(new File("D:\\个人\\code-gen\\springbootdemo\\project"),new File("D:\\个人\\code-gen\\springbootdemo\\"));
        List<String> dir=new ArrayList<>();
        dir.add("controller");
        dir.add("domain");
        dir.add("mapper");
        dir.add("service");
        dir.add("util");
        dir.add("mybatis");
        dir.add("pom");
        dir.add("SwaggerConfig");
        dir.forEach((item)->{
            try {
                if(item.equals("mybatis")){
                    org.aspectj.util.FileUtil.copyDir(new File("D:\\个人\\code-gen\\springbootdemo\\targetFile\\"+item),new File("D:\\个人\\code-gen\\springbootdemo\\demo\\src\\main\\resources\\mybatis"));
                }else if(item.equals("pom")) {
                    org.aspectj.util.FileUtil.copyDir(new File("D:\\个人\\code-gen\\springbootdemo\\targetFile\\"+item),new File("D:\\个人\\code-gen\\springbootdemo\\"+projectName));
                }else if(item.equals("SwaggerConfig")) {
                    org.aspectj.util.FileUtil.copyDir(new File("D:\\个人\\code-gen\\springbootdemo\\targetFile\\"+item),new File(path+"\\"+groupPath));
                }else{
                    org.aspectj.util.FileUtil.copyDir(new File("D:\\个人\\code-gen\\springbootdemo\\targetFile\\"+item),new File(path+"\\"+groupPath+"\\"+item));
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        String name=groupPath.split("\\\\")[2].substring(0,1).toUpperCase()+groupPath.split("\\\\")[2].substring(1);
        FileUtil.copyFile(new File("D:\\个人\\code-gen\\springbootdemo\\targetFile\\"+name+"Application.java"),new File(path+"\\"+groupPath));
        FileUtil.copyFile(new File("D:\\个人\\code-gen\\springbootdemo\\targetFile\\application\\application.yml"),new File("D:\\个人\\code-gen\\springbootdemo\\demo\\src\\main\\resources"));
        ZipUtil.zip("D:\\个人\\code-gen\\springbootdemo\\"+projectName);


    }
    // 去掉参数中的下划线_并将下划线后面的首字母大写
    // flag表示首字母是否大写，true：是，false：否
    String removeIndex(String name,boolean flag){
        // 是否包含下划线
        boolean index=false;
        if(name.contains("_")){
            index=true;
        }
        String[] temp=name.split("_");
        String newName="";
        // 返回字符串首字母大写
        if(flag){
            if(index){
                for(String t:temp){
                    newName+=(t.substring(0,1).toUpperCase()+t.substring(1));
                }
            }else{
                newName=name.substring(0,1).toUpperCase()+name.substring(1);
            }

        }else{
            if(index){
                // 返回字符串首字母小写
                int i=0;
                for(String t:temp){
                    if(i==0){
                        newName+=t.toLowerCase();
                    }else{
                        newName+=t;
                    }
                    i+=1;
                }
            }else{
                newName=name.substring(0,1).toLowerCase()+name.substring(1);
            }

        }
        return newName;
    }
    @Override
    public List<Db> Generate(DbConnectInfo dbConnectInfo){
        List<DbInfo> data=new ArrayList<>();
        try{
            Connection conn = DbUtil.getConnection(dbConnectInfo);
            Statement stmt = conn.createStatement();
            String sql="SELECT	a.TABLE_NAME,a.COLUMN_NAME,	a.ORDINAL_POSITION,	a.COLUMN_DEFAULT,	" +
                    "a.IS_NULLABLE,	a.DATA_TYPE,	a.COLUMN_TYPE,	a.COLUMN_KEY,	a.EXTRA,	" +
                    "a.COLUMN_COMMENT,	b.TABLE_COMMENT FROM	information_schema.`COLUMNS` " +
                    "a LEFT JOIN information_schema.`TABLES`  b on a.TABLE_NAME=b.TABLE_NAME " +
                    "WHERE	a.TABLE_SCHEMA = '"+dbConnectInfo.DbName+"' and  b.table_schema='"+dbConnectInfo.DbName+"'";
            System.out.println(sql);
            ResultSet rs = stmt.executeQuery(sql);
            DbInfo  dbinfo = null;
            while(rs.next()){
                dbinfo = new DbInfo();
                dbinfo.setCOLUMN_NAME(rs.getString("a.COLUMN_NAME"));
                // dbinfo.setORDINAL_POSITION(rs.getString("列的排列顺序"));
                dbinfo.setCOLUMN_DEFAULT(rs.getString("a.COLUMN_DEFAULT"));
                dbinfo.setIS_NULLABLE(rs.getString("a.IS_NULLABLE"));
                dbinfo.setDATA_TYPE(rs.getString("a.DATA_TYPE"));
                dbinfo.setCOLUMN_TYPE(rs.getString("a.COLUMN_TYPE"));
                dbinfo.setCOLUMN_KEY(rs.getString("a.COLUMN_KEY"));
                dbinfo.setEXTRA(rs.getString("a.EXTRA"));
                dbinfo.setCOLUMN_COMMENT(rs.getString("a.COLUMN_COMMENT"));
                dbinfo.setTABLE_NAME(rs.getString("TABLE_NAME"));
                dbinfo.setTABLE_COMMENT(rs.getString("TABLE_COMMENT"));
                data.add(dbinfo);
            }
           
        }catch(Exception e){
          
        }
//        Info info= wash(data);
        List<Db> tables=wash(data);
        String packageNmae=dbConnectInfo.getGroup()+"."+dbConnectInfo.getArtifact();
        // 根据每个表生成对应的文件
        AtomicInteger num= new AtomicInteger();
        tables.forEach((item)->{
            AtomicInteger flag= new AtomicInteger();
//            dbConnectInfo.tableRules.forEach((i)->{
//                // 不显示此表
//                if(item.getTableName().equals(i.getTableName()) && i.getShow()==1){
//                    flag.set(1);
//                    return;
//                }
//            });
//            if(flag.get()==1){
//                return;
//            }
            TemplateData obj=new TemplateData();
            // 类名首字母大写
            obj.setClassName(removeIndex(item.getTableName(),true));
            // 首字母小写
            obj.setClassValue(removeIndex(item.getTableName(),false));
            // 注释
            obj.setTableComment(item.getTableComment());
            obj.setTableName(item.getTableName());
            obj.setDbinfo(item.getDbinfo());

            obj.setPackageName(packageNmae);
            obj.setProjectName(dbConnectInfo.getProjectName());
            obj.setArtifact(dbConnectInfo.getArtifact());
            obj.setDbConnectInfo(dbConnectInfo);
            obj.setRules(dbConnectInfo.getTableRules());
//            VelocityUtil.Generate(obj, num.get());
            num.getAndIncrement();
        });
        String projectPath=System.getProperty("user.dir");
        String spPath=projectPath+"\\"+dbConnectInfo.getArtifact()+"\\src\\main\\java\\";
        System.out.println(spPath);
        try{
            String[] groupArr=dbConnectInfo.getGroup().split("\\.");
            String groupPath=groupArr[0]+"\\"+groupArr[1]+"\\"+dbConnectInfo.getArtifact();
//            moveFile(spPath,groupPath);
        }catch (Exception e){
            System.out.println(e);
        }
        // 清空targetFile目录
        FileUtil.clean("D:\\个人\\code-gen\\springbootdemo\\targetFile");


        return tables;
    }
}